﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using BlueMarineWebClient.BlueMarineService;
using BlueMarineWebClient.DO;

namespace BlueMarineWebClient
{
    public partial class Search : Page
    {
        private static List<vRoomInfo> result;

        private readonly PagedDataSource pds = new PagedDataSource();

        public int CurrentPage
        {
            get
            {
                if (ViewState["CurrentPage"] == null) return 0;
                return Convert.ToInt16(ViewState["CurrentPage"].ToString());
            }
            set { ViewState["CurrentPage"] = value; }
        }

        public int PageCount
        {
            get
            {
                if (ViewState["PageCount"] == null) return 0;
                return Convert.ToInt16(ViewState["PageCount"].ToString());
            }
            set { ViewState["PageCount"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                result = null;
                BindGrid();
                txtDateFrom.Text = DateTime.Today.ToString("dd/MM/yyyy");
                txtDateTo.Text = DateTime.Today.AddDays(1).ToString("dd/MM/yyyy");
                Session["listBooking"] = null;
                lblResult.Visible = false;
                lblSuggestFeature.Visible = false;
                lblSuggestPrice.Visible = false;
            }

            if (Request.QueryString["byDate"] != null)
            {
            }
            if (Request.QueryString["byFeature"] != null)
            {
            }
        }


        private void BindData()
        {
            if (result != null)
            {
                pds.DataSource = result.AsEnumerable();
                dlRoomType.DataSource = pds;
            }
            else
            {
                pds.DataSource = null;
                dlRoomType.DataSource = null;
            }
            pds.AllowPaging = true;
            pds.PageSize = 6;
            pds.CurrentPageIndex = CurrentPage;
            PageCount = pds.PageCount;
            lbtnNext.Enabled = !pds.IsLastPage;
            lbtnPrevious.Enabled = !pds.IsFirstPage;
            lbtnFirst.Enabled = !pds.IsFirstPage;
            lbtnLast.Enabled = !pds.IsLastPage;

            dlRoomType.DataBind();
            doPaging();
        }

        private void BindGrid()
        {
            bookingcart cart = bookingcart.GetCart(Session);
            gvBookingList.DataSource = cart.Items;
            gvBookingList.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            ViewState["CurrentPage"] = null;
            CurrentPage = 0;
            Session["listBooking"] = null;
            BindGrid();
            DateTime inDate = DateTime.ParseExact(txtDateFrom.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            DateTime outDate = DateTime.ParseExact(txtDateTo.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            const int roomTypeId = 0;
            int minPrice = int.Parse(ddlPriceFrom.SelectedValue);
            int maxPrice = int.Parse(ddlPriceTo.SelectedValue);
            if (minPrice > 0 && maxPrice > 0)
            {
                if (minPrice >= maxPrice)
                {
                    lblResult.Text = "<font color=Red>Price is not valid</font>";
                    lblResult.Visible = true;
                    return;
                }
            }
            bool view = chbView.Checked;
            bool bath = chbBath.Checked;
            bool balcony = chbBalcony.Checked;
            result = ServiceBool.ExService.RoomsSearch(inDate, outDate, roomTypeId, minPrice, maxPrice, view, bath,
                                                       balcony);
            if (result.Count > 0)
            {
                lblResult.Text = "Result: " + result.Count + " matched";
                lblResult.Visible = true;
                lblSuggestFeature.Visible = false;
                lblSuggestPrice.Visible = false;
                btnSearchFeatures.Visible = false;
                btnSearchPrice.Visible = false;
                lbtnFirst.Visible = true;
                lbtnPrevious.Visible = true;
                lbtnNext.Visible = true;
                lbtnLast.Visible = true;
                dlPaging.Visible = true;
                BindData();
            }
            else
            {
                lblResult.Visible = true;
                lblResult.Text = "<b>No Room Matched<b>";
                BindData();
                int resultPrice =
                    ServiceBool.ExService.RoomsSearch(inDate, outDate, 0, minPrice, maxPrice, false, false, false).Count;
                int resultFeature =
                    ServiceBool.ExService.RoomsSearch(inDate, outDate, roomTypeId, 0, 0, view, bath, balcony).Count;

                lblSuggestPrice.Visible = true;
                lblSuggestPrice.Text = "<a>" + resultPrice + " Room matched by Price</a>";
                if (resultPrice > 0)
                    btnSearchPrice.Visible = true;

                lblSuggestFeature.Visible = true;
                lblSuggestFeature.Text = "<a>" + resultFeature + " Room matched by Feature</a>";
                if (resultFeature > 0)
                    btnSearchFeatures.Visible = true;
            }
        }

        protected void dlRoomType_SelectedIndexChanged(object sender, EventArgs e)
        {
            var lblroomID = (Label) dlRoomType.SelectedItem.FindControl("lblRoomID");
            int roomID = int.Parse(lblroomID.Text);
            var lblprice = (Label) dlRoomType.SelectedItem.FindControl("lblPrice");
            double price = double.Parse(lblprice.Text);
            DateTime inDate = DateTime.ParseExact(txtDateFrom.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            DateTime outDate = DateTime.ParseExact(txtDateTo.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            bookingcart.GetCart(Session).Add(new bookInfo
                                                 {RoomID = roomID, InDate = inDate, OutDate = outDate, Price = price});

            BindGrid();
        }

        protected void gvBookingList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[4].Text = bookingcart.GetCart(Session).TotalAmount.ToString("c");
            }
        }

        protected void gvBookingList_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            bookingcart.GetCart(Session).Remove(e.RowIndex);
            BindGrid();
        }

        private void doPaging()
        {
            var dt = new DataTable();
            dt.Columns.Add("PageIndex");
            dt.Columns.Add("PageText");
            for (int i = 0; i < pds.PageCount; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = i;
                dr[1] = i + 1;
                dt.Rows.Add(dr);
            }
            dlPaging.DataSource = dt;
            dlPaging.DataBind();
        }

        protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName.Equals("lbtnPaging"))
            {
                CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
                BindData();
            }
        }

        protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            var lbtnPaging = (LinkButton) e.Item.FindControl("lbtnPaging");
            if (lbtnPaging.CommandArgument == CurrentPage.ToString())
            {
                lbtnPaging.Enabled = false;
                lbtnPaging.Font.Bold = true;
            }
        }

        protected void lbtnFirst_Click(object sender, EventArgs e)
        {
            CurrentPage = 0;
            BindData();
        }

        protected void lbtnPrevious_Click(object sender, EventArgs e)
        {
            CurrentPage -= 1;
            BindData();
        }

        protected void lbtnNext_Click(object sender, EventArgs e)
        {
            CurrentPage += 1;
            BindData();
        }

        protected void lbtnLast_Click(object sender, EventArgs e)
        {
            CurrentPage = PageCount - 1;
            BindData();
        }

        protected void btnBook_Click(object sender, EventArgs e)
        {
            Response.Redirect("user/booking.aspx");
        }

        protected void btnSearchPrice_Click(object sender, EventArgs e)
        {
            ViewState["CurrentPage"] = null;
            CurrentPage = 0;
            Session["listBooking"] = null;
            BindGrid();
            DateTime inDate = DateTime.ParseExact(txtDateFrom.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            DateTime outDate = DateTime.ParseExact(txtDateTo.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            const int roomTypeId = 0;
            int minPrice = int.Parse(ddlPriceFrom.SelectedValue);
            int maxPrice = int.Parse(ddlPriceTo.SelectedValue);
            result = ServiceBool.ExService.RoomsSearch(inDate, outDate, roomTypeId, minPrice, maxPrice, false, false,
                                                       false);
            if (result.Count > 0)
            {
                lblResult.Text = "Result: " + result.Count + " matched";
                lblResult.Visible = true;
                
                lbtnFirst.Visible = true;
                lbtnPrevious.Visible = true;
                lbtnNext.Visible = true;
                lbtnLast.Visible = true;
                dlPaging.Visible = true;
                BindData();
            }
            else
            {
                lblResult.Text = "No Room Matched";
                BindData();
            }
        }

        protected void btnSearchFeatures_Click(object sender, EventArgs e)
        {
            ViewState["CurrentPage"] = null;
            CurrentPage = 0;
            Session["listBooking"] = null;
            BindGrid();
            DateTime inDate = DateTime.ParseExact(txtDateFrom.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            DateTime outDate = DateTime.ParseExact(txtDateTo.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            const int roomTypeId = 0;
            bool view = chbView.Checked;
            bool bath = chbBath.Checked;
            bool balcony = chbBalcony.Checked;
            result = ServiceBool.ExService.RoomsSearch(inDate, outDate, roomTypeId, 0, 0, view, bath, balcony);
            if (result.Count > 0)
            {
                lblResult.Text = "Result: " + result.Count + " matched";
                lblResult.Visible = true;
               
                lbtnFirst.Visible = true;
                lbtnPrevious.Visible = true;
                lbtnNext.Visible = true;
                lbtnLast.Visible = true;
                dlPaging.Visible = true;
                BindData();
            }
            else
            {
                lblResult.Text = "No Room Matched";
                BindData();
            }
        }
    }
}